/**
 * @file auth
 * @author
 */

 import store from '@/store';

 const ANONYMOUS_USER = {
   id: null,
   isAuthenticated: false,
   username: 'anonymous',
 };
 
 let currentUser = {
   id: '',
   username: '',
 };
 
 export default {
   /**
    * 未登录状态码
    */
   HTTP_STATUS_UNAUTHORIZED: 401,
 
   /**
    * 获取当前用户
    *
    * @return {Object} 当前用户信息
    */
   getCurrentUser() {
     return currentUser;
   },
 
   redirectToLogin() {
     // const callbackUrl = `${location.origin}/static/login_success.html?is_ajax=1`;
     const callbackUrl = encodeURIComponent(window.location.href);
     const appCode = window.PROJECT_CONFIG.BKPAAS_APP_ID || BKPAAS_APP_ID;
     const loginUrl = window.PROJECT_CONFIG.BK_LOGIN_URL || BK_LOGIN_URL;
     window.location.href = `${loginUrl}?app_id=${appCode}&c_url=${callbackUrl}`;
   },
 
   /**
    * 请求当前用户信息
    *
    * @return {Promise} promise 对象
    */
   requestCurrentUser() {
     let promise = null;
     if (currentUser.isAuthenticated) {
       promise = new Promise((resolve) => {
         resolve(currentUser);
       });
     } else {
       if (!store.state.user || !Object.keys(store.state.user).length) {
         // store action userInfo 里，如果请求成功会更新 state.user
         const req = store.dispatch('userInfo');
         promise = new Promise((resolve, reject) => {
           req.then(() => {
             // 存储当前用户信息(全局)
             currentUser = store.getters.user;
             currentUser.isAuthenticated = true;
             resolve(currentUser);
           }, (err) => {
             if (err.response.status === this.HTTP_STATUS_UNAUTHORIZED || err.crossDomain) {
               resolve({ ...ANONYMOUS_USER });
             } else {
               reject(err);
             }
           });
         });
       }
     }
 
     return promise;
   },
 };
 